package org.prs.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.validator.GenericValidator;
import org.prs.model.Child;
import org.prs.model.Guardian;
import org.prs.model.NextOfKin;
import org.prs.model.User;
import org.prs.model.WorkerComments;
import org.prs.persistence.ChildDatabasePersitenceManager;
import org.prs.persistence.GuardianDatabasePersistence;
import org.prs.persistence.NextOfKinDatabasePersistence;
import org.prs.persistence.WorkerCommentsDatabasePersistence;

public class NewChildServlet extends HttpServlet {

    private Child newChild = new Child();
    private ChildDatabasePersitenceManager persistChild = new ChildDatabasePersitenceManager();
    private GuardianDatabasePersistence manageGuardian = new GuardianDatabasePersistence();
    private NextOfKinDatabasePersistence persistNextOfKin = new NextOfKinDatabasePersistence();
    private WorkerCommentsDatabasePersistence persistWorkerComments = new WorkerCommentsDatabasePersistence();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(true);
            User loggedUser = (User) session.getAttribute("loggedinuser");
            if (loggedUser == null) {
                response.sendRedirect("index.jsp");
                return;
            } else {
                newChild.setCreatorId(loggedUser.getUserId());
            }
            newChild.setLastName(request.getParameter("lastname"));
            newChild.setFirstName(request.getParameter("firstname"));
            try {
                newChild.setDateOfBirth(new SimpleDateFormat("dd/MM/yyyy").parse(request.getParameter("dateofbirth")));
            } catch (ParseException e) {
            }
            newChild.setAddress(request.getParameter("address"));
            newChild.setChildCode(request.getParameter("childcode"));
            newChild.setDistrict(request.getParameter("district"));
            newChild.setGender(request.getParameter("gender"));
            newChild.setPhoneNumber(request.getParameter("dateofbirth"));
            newChild.setMiddleName(request.getParameter("middlename"));
            newChild.setResidence(request.getParameter("residence"));
            try {
                newChild.setSchoolStageId(Integer.parseInt(request.getParameter("stage")));
            } catch (NumberFormatException e) {
            }
            boolean valid = true;
            StringBuilder childCreationMessage = new StringBuilder();

            if (GenericValidator.isBlankOrNull(newChild.getLastName())) {
                valid = false;
                childCreationMessage.append("<div id='inputerror'>Last Name is null</div>");
            }
            if (GenericValidator.isBlankOrNull(newChild.getFirstName())) {
                valid = false;
                childCreationMessage.append("<div id='inputerror'>First Name is null</div>");
            }
            if (!valid) {
                session.setAttribute("childcreationmsg", childCreationMessage.toString());
                response.sendRedirect("newChild.jsp");
            } else {
                boolean inserted = persistChild.insertChild(newChild);
                if (inserted) {

                    boolean insertNextOfKin = true;
                    boolean insertGuardian = true;
                    boolean insertWorkerComments = true;
                    if (!GenericValidator.isBlankOrNull(request.getParameter("parentname"))) {
                        Guardian guardian = new Guardian();
                        guardian.setChildId(persistChild.getChildrenCount());
                        String names[] = request.getParameter("parentname").split(" ");
                        for (int j = 0; j < names.length; j++) {
                            if (j == 0) {
                                guardian.setFirstName(names[j]);
                            }
                            if (j == 1) {
                                guardian.setMiddleName(names[j]);
                            }
                            if (j == 2) {
                                guardian.setLastName(names[j]);
                            }
                        }
                        try {
                            guardian.setRelationshipTypeId(Integer.parseInt(request.getParameter("relationship")));
                        } catch (NumberFormatException e) {
                        }
                        insertGuardian = manageGuardian.insertGuardian(guardian);

                    }
                    if (!GenericValidator.isBlankOrNull(request.getParameter("nextofkinname"))) {
                        NextOfKin nextOfKin = new NextOfKin();
                        nextOfKin.setChildId(persistChild.getChildrenCount());
                        String names[] = request.getParameter("nextofkinname").split(" ");
                        for (int j = 0; j < names.length; j++) {
                            if (j == 0) {
                                nextOfKin.setFirstName(names[j]);
                            }
                            if (j == 1) {
                                nextOfKin.setMiddleName(names[j]);
                            }
                            if (j == 2) {
                                nextOfKin.setLastName(names[j]);
                            }
                        }
                        try {
                            nextOfKin.setRelationshipTypeId(Integer.parseInt(request.getParameter("nextofrelationship")));
                        } catch (NumberFormatException e) {
                        }
                        insertNextOfKin = persistNextOfKin.insertNextOfKin(nextOfKin);

                    }
                    if (!GenericValidator.isBlankOrNull(request.getParameter("workercomments"))) {
                        WorkerComments workerComments = new WorkerComments();
                        workerComments.setChildId(persistChild.getChildrenCount());
                        workerComments.setWorkerId(loggedUser.getUserId());
                        workerComments.setDetails(request.getParameter("workercomments"));
                        insertWorkerComments = persistWorkerComments.insertWorkerComments(workerComments);

                    }
                    if (insertGuardian && insertNextOfKin && insertWorkerComments) {
                        childCreationMessage.append("<div id='inputsuccess'>The child was created successfully</div>");
                        session.setAttribute("childcreationmsg", childCreationMessage.toString());
                        response.sendRedirect("newChild.jsp");
                    } else {
                        childCreationMessage.append("<div id='inputerror'>Errors occurred during child creation</div>");
                        session.setAttribute("childcreationmsg", childCreationMessage.toString());
                        response.sendRedirect("newChild.jsp");
                    }


                }

            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
